package com.ruoyi.common.config.websockert3;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import javax.annotation.PreDestroy;

/**
 * @author Fql18
 * @version 1.0
 * @date 2025-08-19 23:27
 * @description
 */
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "websocket")
public class WebSocketClientHandler extends StandardWebSocketClient implements WebSocketHandler {
	private WebSocketSession session;
	private String url;

	/**
	 * 连接WebSocket服务端
	 */
//    @Scheduled(fixedDelay = 60000) // 每隔1分钟连接一次
	public void connect() throws Exception {
		WebSocketClient client = new StandardWebSocketClient();
		session = client.doHandshake(new WebSocketClientHandler(), url).get();
		log.info("Client: WebSocket connection established");
	}

	/**
	 * 关闭WebSocket连接
	 */
	@PreDestroy
	public void close() throws Exception {
		session.close();
	}

	/**
	 * @param message:向服务端发送的消息
	 */
	public void sendMessage(String message) throws Exception {
		session.sendMessage(new TextMessage(message));
	}

//    @Scheduled(fixedDelay = 5000)
//    public void sendMessage() throws Exception {
//        session.sendMessage(new TextMessage("message"));
//    }

	/**
	 * 处理连接后的逻辑
	 * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		log.info("Client: WebSocket connection established");
	}
	/**
	 * 处理客户端发送的消息
	 * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
	 * @param message:客户端发送的文本消息
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		log.info("Client: Received message: " + message.getPayload());
		session.sendMessage(new TextMessage("Client: Hello, server!"));
	}

	/**
	 * 处理发生的错误
	 * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
	 * @param exception:通信出现的异常
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		log.info("Client: Error Occurred: " + exception.getMessage());
	}

	/**
	 * 连接关闭
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		log.info("Client: Connection Closed");
	}

	/**
	 * 用于判断服务器或客户端是否支持分片消息partial message
	 * WebSocket 协议规范要求所有的 WebSocket 实现都必须支持接收和处理完整的消息
	 * @return boolean
	 */
	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
}
